package com.cardpay.bill;

import com.cardpay.common.log.Log;
import com.cardpay.common.util.CharacterUtil;
import com.cardpay.common.util.ConstantUtil;
import com.cardpay.common.util.ValidateUtil;
import com.cardpay.page.PageBean;
import com.cardpay.supplier.Supplier;
import com.cardpay.supplier.SupplierService;
import org.slf4j.Logger;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class BillServlet
 */
@WebServlet("/BillServlet")
public class BillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final Logger log = Log.get();

	private static final String METHOD_ADD_UI = "ADD_UI";
	private static final String METHOD_ADD = "ADD";
	private static final String METHOD_DEL = "DEL";
	private static final String METHOD_UPDATE_UI = "UPDATE_UI";
	private static final String METHOD_UPDATE = "UPDATE";
	private static final String METHOD_LIST = "LIST";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");

		String method=request.getParameter("method");

		log.debug("Servlet：请求参数：method={}", method);
		if (CharacterUtil.isEmpty(method)) {
			log.error("访问路径缺少method参数！");
			return;
		}
		else if (METHOD_ADD_UI.equals(method)) {
			this.addUI(request, response);
		}
		else if (METHOD_ADD.equals(method)) {
			this.add(request, response);
		}
		else if (METHOD_DEL.equals(method)) {
			this.del(request, response);
		}
		else if (METHOD_UPDATE_UI.equals(method)) {
			this.updateUI(request, response);
		}
		else if (METHOD_UPDATE.equals(method)) {
			this.update(request, response);
		}
		else if (METHOD_LIST.equals(method)) {
			this.list(request, response);
		}
		else {
			log.error("请求地址的method参数不正确！");
			return;
		}
	}

	// 添加账单页面（准备页面上所需的数据）
	private void addUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SupplierService supplierService = new SupplierService();
		List<Supplier> supplierList = supplierService.findAll(); // 查询出添加账单页面上所需的角色列表信息

		request.setAttribute("supplierList", supplierList);
		request.getRequestDispatcher("add.jsp").forward(request, response);
	}

	// 新增账单信息
	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String name = request.getParameter("name");
		int num = Integer.valueOf(request.getParameter("num"));
		String unit = request.getParameter("unit");
		double money = Double.valueOf(request.getParameter("money"));
		String isPayment = request.getParameter("isPayment");
		String supplierId= request.getParameter("supplierId");
		String descriptions = request.getParameter("descriptions");

		// 数据校验
		if (!ValidateUtil.validateName(name)) {
			log.error("Servlet：数据校验失败，商品名称不符合要求！");
			// response.sendRedirect("");
			return;
		}

		if (!CharacterUtil.isEmpty(unit) && !(unit.length()<=10)) {
			log.error("Servlet：数据校验失败，交易单位不符合要求！");
			return;
		}

		if (!CharacterUtil.isEmpty(descriptions) && descriptions.length() > 140) {
			log.error("Servlet：数据校验失败，备注长度不符合要求！");
			return;
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat(ConstantUtil.LONG_TIME_FORMAT);

		// 封装数据
		Bill bill = new Bill();
		bill.setName(name);
		bill.setNum(num);
		bill.setUnit(unit);
		bill.setMoney(money);
		bill.setIsPayment(isPayment);
		bill.setSupplierId(supplierId);
		bill.setDescriptions(descriptions);
		bill.setCreateTime(dateFormat.format(new Date()));

		BillService billService = new BillService();
		// 新增数据
		if (billService.add(bill)) {
			response.sendRedirect("BillServlet?method=LIST");
		}
		else {
			log.error("Serlvet：新增账单信息失败！");
		}
	}

	// 删除账单信息
	private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
			log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
			return;
		}

		BillService billService = new BillService();
		Bill bill = billService.find(id);

		if (null == bill) {
			log.error("Serlvet：数据校验失败，待删除的账单不存在！");
			return;
		}

		// 执行删除
		if (billService.delete(id)) {
			response.sendRedirect("BillServlet?method=LIST");
		}
		else {
			log.error("删除账单信息失败！");
		}
	}

	// 查看账单的详细信息（准备编辑账单页面的数据）
	private void updateUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
			log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
			return;
		}

		BillService billService = new BillService();
		Bill bill = billService.find(id); // 查询出待查看（编辑）的账单信息

		SupplierService supplierService = new SupplierService();
		List<Supplier> supplierList = supplierService.findAll();

		request.setAttribute("bill", bill);
		request.setAttribute("supplierList", supplierList);
		request.getRequestDispatcher("update.jsp").forward(request, response);
	}

	// 更新账单信息
	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		int num = Integer.valueOf(request.getParameter("num"));
		String unit = request.getParameter("unit");
		double money = Double.valueOf(request.getParameter("money"));
		String isPayment = request.getParameter("isPayment");
		String supplierId= request.getParameter("supplierId");
		String descriptions = request.getParameter("descriptions");

		// 数据校验
		if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
			log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
			return;
		}

		BillService billService = new BillService();
		Bill bill=billService.find(id);

		if (null == bill) {
			log.error("Servlet：数据校验失败，待更新的账单不存在！");
			return;
		}

		// 数据校验
		if (!ValidateUtil.validateName(name)) {
			log.error("Servlet：数据校验失败，商品名称不符合要求！");
			// response.sendRedirect("");
			return;
		}

		if (!CharacterUtil.isEmpty(unit) && !(unit.length()<=10)) {
			log.error("Servlet：数据校验失败，交易单位不符合要求！");
			return;
		}

		if (!CharacterUtil.isEmpty(descriptions) && descriptions.length() > 140) {
			log.error("Servlet：数据校验失败，备注长度不符合要求！");
			return;
		}

		SimpleDateFormat dateFormat = new SimpleDateFormat(ConstantUtil.LONG_TIME_FORMAT);

		// 封装数据
		bill = new Bill();
		bill.setId(id);
		bill.setName(name);
		bill.setNum(num);
		bill.setUnit(unit);
		bill.setMoney(money);
		bill.setIsPayment(isPayment);
		bill.setSupplierId(supplierId);
		bill.setDescriptions(descriptions);

		// 更新数据
		if (billService.update(bill)) {
			response.sendRedirect("BillServlet?method=LIST");
		}
		else {
			log.error("Serlvet：修改（更改）账单信息失败！");
		}
	}

	// 查询账单列表
	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pageNumStr = request.getParameter("pageNum"); // 当前页码
		String queryName = request.getParameter("queryName"); // 页面上的查询条件（根据商品名称进行查询）

		if (null != queryName) {
			// request.getParameter(...)会进行第一次解码
			// 再调用 java.net.URLDecoder.decode(String s, String enc) 方法进行第二次解码
			queryName = URLDecoder.decode(queryName, "UTF-8");
		}

		int pageNum = 1; // 当前页码（默认为第1页）
		if (CharacterUtil.isNumber(pageNumStr)) {
			pageNum = Integer.parseInt(pageNumStr);
		}

		BillService billService = new BillService();
		// 分页查询
		PageBean<Bill> pageBean = billService.findPagingBills(pageNum, queryName);

		request.setAttribute("queryName", queryName); // 回显查询条件
		request.setAttribute("pageBean", pageBean);
		request.getRequestDispatcher("list.jsp").forward(request, response);
	}


}
